package com.aioething.iot.framework;

import cn.hutool.http.HttpStatus;
import com.aioething.iot.beans.Result;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@ControllerAdvice
public class GlobalExceptionAdvice {
    @ExceptionHandler(Exception.class)
    public void defaultErrorHandler(HttpServletRequest request, HttpServletResponse response, Exception e) throws IOException {
        response.setStatus(HttpStatus.HTTP_INTERNAL_ERROR);
        response.setCharacterEncoding("UTF-8");
        response.addHeader("Content-Type", "application/json;charset=UTF-8");
        response.getWriter().write(JSONObject.toJSONString(Result.Error(HttpStatus.HTTP_INTERNAL_ERROR, null == e.getMessage() ? "未知异常" : e.getMessage())));
        response.getWriter().flush();
        response.getWriter().close();
    }
}
